package com.geping.etl.common.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.geping.etl.common.entity.Sys_Department;
import com.geping.etl.common.entity.Sys_UserAndOrgDepartmentVo;
import com.geping.etl.common.repository.Sys_DepartmentRepository;
import com.geping.etl.common.util.Constants;
import com.geping.etl.common.vo.PersonBankEmailVo;
import com.geping.etl.utils.EnvUitl;
import com.geping.etl.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.geping.etl.common.entity.Sys_UserAndOrgDepartment;
import com.geping.etl.common.repository.Sys_UserAndOrgDepartmentRepository;
import com.geping.etl.common.service.Sys_UserAndOrgDepartmentService;

@Service
@Transactional
@Slf4j
public class Sys_UserAndOrgDepartmentServiceImpl implements Sys_UserAndOrgDepartmentService {

	
	@Autowired
	private Sys_UserAndOrgDepartmentRepository sys_UserAndDepartmentRepository;

	@Autowired
	private Sys_DepartmentRepository sysDepartmentRepository;
	
	@Override
	public List<Sys_UserAndOrgDepartment> findAllSysUser() {
		
		return sys_UserAndDepartmentRepository.findAllSysUser().stream().distinct().collect(Collectors.toList());
	}

	
	
	//模糊查询(在未删除的用户中查询)
    public List<Sys_UserAndOrgDepartment> findSysUserByName(String usercname){
    	
    	return sys_UserAndDepartmentRepository.findSysUserByName(usercname);
    }



	@Override
	public List<Sys_UserAndOrgDepartment> findSysUserByLoginID(String LoginId) {
		// TODO Auto-generated method stub
		return sys_UserAndDepartmentRepository.findSysUserByLoginID(LoginId);
	}


	//登录
	public Sys_UserAndOrgDepartment findSysUserLogin(String loginId,String password){
		
		return sys_UserAndDepartmentRepository.findSysUserLogin(loginId, password);
	}

	@Override
	public void synUserInfoToPersonBank() {
		//1.查询用户表所有员工信息，并将员工通过部门进行分组
		List<Sys_UserAndOrgDepartment> userAndOrgDepartments = sys_UserAndDepartmentRepository.findAllSysUser();

		//2.新建机构号，分行号，邮箱等分组对象
		Map<String, Map<String, List<String>>> orgAndDeptMap = new HashMap<>();
		userAndOrgDepartments.forEach(user -> {
			if(orgAndDeptMap.get(user.getOrgid())!=null){
				groupOrgId(orgAndDeptMap, user);
			}else{
				orgAndDeptMap.put(user.getOrgid(), new HashMap<>());
				groupOrgId(orgAndDeptMap, user);
			}
		});

		//4.新建部门Id和部门名称对象
		Map<String, String> deptMap = new HashMap<>();
		List<Sys_Department> departments = sysDepartmentRepository.findAllSysDepartment();
		departments.forEach(dept -> {
			String deptId = dept.getDepartmentId().substring(0, 7);
			deptMap.put(deptId, dept.getDescription());
		});

		PersonBankEmailVo personBankEmailVo = new PersonBankEmailVo();
		personBankEmailVo.setOrgAndDeptMap(orgAndDeptMap);
		personBankEmailVo.setDeptMap(deptMap);


		//5.将分组好的信息同步到个人银行，供ftp获取数据时使用
		String url = EnvUitl.props.getProperty(Constants.SYSTEM_PERSON_BANK_PROJECT) + Constants.PERSON_BANK_EMAIL_INFO;
		String jsonString = JSONObject.toJSONString(personBankEmailVo);
		log.info("synUserInfoToPersonBank syn start, url = {}, jsonString = {}", url, jsonString);
		String result = HttpUtil.postRequestAddHeaderAndRetry(url, jsonString, null);
		log.info("synUserInfoToPersonBank syn end, url = {}, jsonString = {}, result = {}", url, jsonString, result);

	}


	@Override
	public void synUserInfoToCrs() {
		//4.新建部门Id和部门名称对象
		Map<String, String> deptMap = new HashMap<>();
		List<Sys_Department> departments = sysDepartmentRepository.findAllSysDepartment();
		departments.forEach(dept -> {
			String deptId = dept.getDepartmentId().substring(0, 7);
			deptMap.put(deptId, dept.getDescription());
		});

		PersonBankEmailVo personBankEmailVo = new PersonBankEmailVo();
		personBankEmailVo.setDeptMap(deptMap);


		//5.将分组好的信息同步到个人银行，供ftp获取数据时使用
		String url = EnvUitl.props.getProperty(Constants.SYSTEM_CRS_PROJECT) + Constants.CRS_DEPT_INFO;
		String jsonString = JSONObject.toJSONString(personBankEmailVo);
		log.info("synUserInfoToPersonBank syn start, url = {}, jsonString = {}", url, jsonString);
		String result = HttpUtil.postRequestAddHeaderAndRetry(url, jsonString, null);
		log.info("synUserInfoToPersonBank syn end, url = {}, jsonString = {}, result = {}", url, jsonString, result);

	}

	private void groupOrgId(Map<String, Map<String, List<String>>> orgAndDeptMap, Sys_UserAndOrgDepartment user) {
		try {
			Map<String, List<String>> deptMap = orgAndDeptMap.get(user.getOrgid());
			String deptId = user.getDepartid().substring(0, 7);
			//判断是不是上海分行的IT部门
			if (Constants.TAIWAN_SHANGHAI_BANK_NO.equals(deptId)
					&& user.getDepartmentname().contains(Constants.TAIWAN_DEPT_IT_NAME)) {
				deptId = Constants.TAIWAN_DEPT_IT_NAME;
			}
			if (deptMap.get(deptId) != null) {
				groupDeptId(user, deptMap, deptId);
			} else {
				deptMap.put(deptId, new ArrayList<>());
				groupDeptId(user, deptMap, deptId);
			}
		}catch (Exception e){
			log.error("synUserInfoToPersonBank groupOrgId exception, user = {}, e = {}", user, e);
			throw e;
		}
	}

	private void groupDeptId(Sys_UserAndOrgDepartment user, Map<String, List<String>> deptMap, String deptId) {
		List<String> emails = deptMap.get(deptId);
		if(StringUtils.isNotBlank(user.getEmail())) {
			emails.add(user.getEmail());
		}else{
			log.error("synUserInfoToPersonBank groupDeptId email is null, loginId = {}", user.getLoginid());
		}
	}
}
